package com.code.google.p.jyve.berekeningen;

class EenwaardigZwakkeBerekening extends ZwakkeBerekening {

	@Override
	public double berekenVanuitTitrant(double titrant) {
		double pH = 7;
		double volTot = (mVolumeOplossing + titrant) / 1e3;
		titrant /= 1e3;

		if (mTypeStof == ZUUR){
			if (mMolariteitOplossing * mVolumeOplossing/1e3 > mMolariteitTitrant * titrant){
				double a = 1;
				double b = volTot * mKz[0] - mMolariteitTitrant * titrant + (1e-7) * mVolumeOplossing/1e3;
				double c = -mMolariteitOplossing * mVolumeOplossing/1e3 * volTot * mKz[0];

				double x = abcMax(a, b, c);

				pH = -Math.log10((x - mMolariteitTitrant * titrant + (1e-7) * mVolumeOplossing/1e3) / volTot);
			}
			else{
				double Kb = kzToKb(mKz[0]);
				double a = 1;
				double b = mMolariteitTitrant * titrant - mMolariteitOplossing * mVolumeOplossing/1e3 + Kb * volTot;
				double c = -mMolariteitOplossing * mVolumeOplossing/1e3 * volTot * Kb;
				double x = abcMax(a, b, c);

				double pOH = -Math.log10((x + mMolariteitTitrant * titrant - mMolariteitOplossing * mVolumeOplossing/1e3)/ (volTot));

				pH = 14 - pOH;
			}
		}
		else{
			//TODO: checken berekening basen
			if (mMolariteitOplossing * mVolumeOplossing/1e3 > mMolariteitTitrant * titrant){
				double a = 1;
				double b = volTot * mKz[0] - mMolariteitTitrant * titrant + (1e-7) * mVolumeOplossing/1e3;
				double c = -mMolariteitOplossing * mVolumeOplossing/1e3 * volTot * mKz[0];

				double x = abcMax(a, b, c);

				double pOH = -Math.log10((x - mMolariteitTitrant * titrant + (1e-7) * mVolumeOplossing/1e3) / volTot);
				pH = 14 - pOH;
			}
			else{			
				double Kb = kzToKb(mKz[0]);
				double a = 1;
				double b = mMolariteitTitrant * titrant - mMolariteitOplossing * mVolumeOplossing/1e3 + Kb * volTot;
				double c = -mMolariteitOplossing * mVolumeOplossing/1e3 * volTot * Kb;
				double x = abcMax(a, b, c);

				pH = -Math.log10((x + mMolariteitTitrant * titrant - mMolariteitOplossing * mVolumeOplossing/1e3)/ (volTot));
			}
		}
		return pH;
	}
}
